package com.xishu.util;

import com.xishu.exception.ResponseStatusException;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * 执行操作系统命令
 */
public class CmdUtil {
    private static Logger logger = LoggerFactory.getLogger(CmdUtil.class);

    /**
     * 执行操作系统命令
     *
     * @param cmd
     * @return
     */
    public static int execute(String cmd) {
        try {
            logger.info("will execute cmd {}", cmd);
            Runtime run = Runtime.getRuntime();
            Process process = run.exec(cmd);
            InputStream in = process.getInputStream();
            while (in.read() != -1) {
                //System.out.println(in.read());
            }
            in.close();
            process.waitFor();
            return 0;
        } catch (Exception e) {
            logger.info("e", e);
            return 1;
        }
    }

    /**
     * 执行命令
     *
     * @param file
     * @return
     */
    public static int executeShellCmd(File file) {
        return execute(String.format("/bin/bash %s", file.getAbsolutePath()));
    }

    /**
     * 执行命令
     *
     * @param cmd
     * @return
     */
    public static int executeShellCmd(String cmd) throws Exception {
        File file = generateShellCmdFile(cmd);
        return executeShellCmd(file);
    }

    /**
     * 先将命令写到文件里面，然后再执行shell命令
     *
     * @param cmd
     * @return
     */
    public static File generateShellCmdFile(String cmd) throws ResponseStatusException, IOException {
        logger.info("cmd is {}", cmd);
        File tmpFile = MongoId.getInstance().generateTmpFile("sh");
        FileOutputStream fileOutputStream = new FileOutputStream(tmpFile);
        try {
            fileOutputStream.write(cmd.getBytes());
        } finally {
            IOUtils.closeQuietly(fileOutputStream);
        }

        return tmpFile;
    }
}
